using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using CoachingOrganizer.Logic.Models.Tools.EmotionsPack;
using CoachingOrganizer.Android.Helpers;
using CoachingOrganizer.Android.Hardware;
using CoachingOrganizer.Android.Adapters.Tools.EmotionsPack;

namespace CoachingOrganizer.Android.Activities.Tools.EmotionsPack
{
    [Activity(Label = "@string/ApplicationName")]
    public class EmotionsPackDetailsActivity : Activity
    {
        private EmotionsPackModel _model;
        private CameraVideoViewWrapper _cameraWrapper;

        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);
            _model = UIHelper.GetActivityModel<EmotionsPackModel>(this, bundle);
            SetContentView(Resource.Layout.EmotionsPackDetailsLayout);
            InitLayout();
            Init();
            HookModel();
        }

        protected override void OnResume()
        {
            base.OnResume();
            //HookModel();
        }

        protected override void OnPause()
        {
            base.OnPause();
            //UnhookModel();
        }

        private void InitLayout()
        {
            TabHost emotionsPackTabHost = FindViewById<TabHost>(Resource.Id.emotionsPackTabHost);
            emotionsPackTabHost.Setup();
            TabHost.TabSpec spec = emotionsPackTabHost.NewTabSpec("tab1");
            spec.SetContent(Resource.Id.emotionsPackChooseLinearLayout);
            spec.SetIndicator(Resources.GetString(Resource.String.EmotionsPackChoose));
            emotionsPackTabHost.AddTab(spec);
            spec = emotionsPackTabHost.NewTabSpec("tab2");
            spec.SetContent(Resource.Id.emotionsPackTraceLinearLayout);
            spec.SetIndicator(Resources.GetString(Resource.String.EmotionsPackTrace));
            emotionsPackTabHost.AddTab(spec);
            spec = emotionsPackTabHost.NewTabSpec("tab3");
            spec.SetContent(Resource.Id.emotionsPackGalleryLinearLayout);
            spec.SetIndicator(Resources.GetString(Resource.String.EmotionsPackGallery));
            emotionsPackTabHost.AddTab(spec);
        }

        private async void Init()
        {
            using (System.Threading.CancellationTokenSource cancellation = new System.Threading.CancellationTokenSource())
                await _model.LoadTraceItemsAsync(cancellation.Token);
        }

        private void HookModel()
        {
            _model.EmotionsTrace.SelectedCameraIndexChanged += EmotionsTrace_SelectedCameraIndexChanged;
            VideoView emotionsPackTraceVideoView = FindViewById<VideoView>(Resource.Id.emotionsPackTraceVideoView);
            _cameraWrapper = new CameraVideoViewWrapper(emotionsPackTraceVideoView);
            _cameraWrapper.SnapshotFailed += CameraWrapper_SnapshotFailed;
            _model.SelectedEmotionChanged += Model_SelectedEmotionChanged;
            ExpandableListView emotionsExpandableListView = FindViewById<ExpandableListView>(Resource.Id.emotionsExpandableListView);
            emotionsExpandableListView.SetAdapter(new EmotionsPackAdapter(this, _model));
            Spinner emotionsPackTraceCamerasSpinner = FindViewById<Spinner>(Resource.Id.emotionsPackTraceCamerasSpinner);
            emotionsPackTraceCamerasSpinner.Adapter = new CamerasAdapter(this, _model.EmotionsTrace);
            Button saveEmotionTraceButton = FindViewById<Button>(Resource.Id.saveEmotionTraceButton);
            saveEmotionTraceButton.Click += SaveEmotionTraceButton_Click;
            Gallery emotionsPackGallery = FindViewById<Gallery>(Resource.Id.emotionsPackGallery);
            emotionsPackGallery.Adapter = new EmotionsPackGalleryAdapter(this, _model);
            Button removeEmotionTraceItemButton = FindViewById<Button>(Resource.Id.removeEmotionTraceItemButton);
            removeEmotionTraceItemButton.Click += (sender, e) =>
            {
                IEnumerable<EmotionTraceItemModel> items = _model.EnumerateEmotionTraceItems();
                EmotionTraceItemModel traceItem = items == null ? null : items.ElementAtOrDefault(emotionsPackGallery.SelectedItemPosition);
                if (traceItem != null)
                    traceItem.Remove();
            };
        }

        private void Model_SelectedEmotionChanged(object sender, EventArgs e)
        {
            EmotionTraceModel selectedEmotion = _model.SelectedEmotion;
            TextView emotionNameInTraceTextView = FindViewById<TextView>(Resource.Id.emotionNameInTraceTextView);
            emotionNameInTraceTextView.Text = selectedEmotion == null ? string.Empty : selectedEmotion.EmotionName;
            TextView emotionNameInGalleryTextView = FindViewById<TextView>(Resource.Id.emotionNameInGalleryTextView);
            emotionNameInGalleryTextView.Text = selectedEmotion == null ? string.Empty : selectedEmotion.EmotionName;
        }

        private void EmotionsTrace_SelectedCameraIndexChanged(object sender, EventArgs e)
        {
            _cameraWrapper.CurrentCameraIndex = _model.EmotionsTrace.SelectedCameraIndex;
        }

        private void SaveEmotionTraceButton_Click(object sender, EventArgs e)
        {
            EmotionTraceModel selectedEmotion = _model.SelectedEmotion;
            if (selectedEmotion == null)
            {
                using (Toast errorToast = Toast.MakeText(ApplicationContext, Resource.String.NoEmotionToTraceError, ToastLength.Short))
                    errorToast.Show();
                return;
            }
            EditText emotionTraceItemNameEditText = FindViewById<EditText>(Resource.Id.emotionTraceItemNameEditText);
            string traceItemName = emotionTraceItemNameEditText.Text;
            if (string.IsNullOrWhiteSpace(traceItemName))
                emotionTraceItemNameEditText.Text = traceItemName = (selectedEmotion.TraceItems.Count() + 1).ToString();
            _cameraWrapper.BeginSnapshotToJpeg(data => RunOnUiThread((() =>
                selectedEmotion.AddNewTraceItem(traceItemName, data))));
        }

        private void CameraWrapper_SnapshotFailed(object sender, EventArgs e)
        {
            using (Toast errorToast = Toast.MakeText(ApplicationContext, Resource.String.NoEmotionTracePictureError, ToastLength.Short))
                errorToast.Show();
        }
    }
}